package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Jetwang
 * @date: 2022/4/11 16:34
 * @description: DishServiceImpl
 * @version: 1.0
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    private DishMapper dishMapper;
    private DishFlavorService dishFlavorService;

    @Autowired
    public void setDishFlavorService(DishFlavorService dishFlavorService) {
        this.dishFlavorService = dishFlavorService;
    }

    @Autowired
    public void setDishMapper(DishMapper dishMapper) {
        this.dishMapper = dishMapper;
    }

    @Override
    public void updateStatusByIds(Integer status, List<Long> ids) {
        dishMapper.updateStatusById(status, ids);
    }

    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        // 保存到dish表
        this.save(dishDTO);
        // 获取菜品id
        Long id = dishDTO.getId();
        // 保存到dish_flavor表
        List<DishFlavor> dishFlavors = dishDTO.getFlavors().stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(dishFlavors);
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        // 更新dish表
        this.updateById(dishDTO);
        // 更新dish_flavor表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDTO.getId());
        // 1. 先清理
        dishFlavorService.remove(lqw);
        // 2. 再插入提交的口味数据
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDTO.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }
}
